//
//  AUProtocol_Cache.swift
//  AwesomeUBaseModule_Example
//
//  Created by Miss_Special on 2018/4/13.
//  Copyright © 2018 CocoaPods. All rights reserved.
//

// MARK: - Protocol
public protocol AUProtocol_Cache { }

// MARK: - UserDefaults
public extension AUProtocol_Cache {
    
    /// account file path
    fileprivate var au_cache_accountPath: String {
        let accountPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first!
        return (accountPath as NSString).appendingPathComponent("kAUProtocol_Cache.plist")
    }
    
    /// 本地_存
    func cache_save(_ someObject: Any?, forKey key: String) {
        let userDefault = UserDefaults.standard
        userDefault.set(someObject, forKey: key)
        print("---本地_存储---")
    }
    
    /// 本地_取
    func cache_get(forKey key: String) -> Any? {
        return UserDefaults.standard.object(forKey: key)
    }
    
    /// 本地_删_普通
    func cache_remove_normal(forKey key: String) {
        let userDefault = UserDefaults.standard
        userDefault.removeObject(forKey: key)
        print("---本地_删除_普通---")
    }
    
    /// 本地_删_归档
    func cache_remove_archive(atPath path: String = "") {
        let filePath = path.isEmpty ? au_cache_accountPath : path
        if FileManager.default.fileExists(atPath: filePath) {
            try? FileManager.default.removeItem(atPath: filePath)
            print("---本地_删除_归档---")
            return
        }
        print("---文件不存在---")
    }
    
    /// 本地_解档
    func cache_unarchive(forKey key: String, atPath path: String = "") -> Any? {
        let filePath = path.isEmpty ? au_cache_accountPath : path
        if FileManager.default.fileExists(atPath: filePath) {
            let url = URL(fileURLWithPath: filePath)
            if let data = try? Data(contentsOf: url) {
                let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
                let result = unarchiver.decodeObject(forKey: key)
                unarchiver.finishDecoding()
                print("---本地_解档---")
                return result
//                self = result as! Self
            }
        }
        print("---文件不存在---")
        return nil
    }
}

// MARK: - Archive
public extension AUProtocol_Cache where Self: NSCoding, Self: NSObject {
    
    /// 本地_归档
    @discardableResult func cache_archive(forKey key: String, atPath path: String = "") -> Bool {
        print("---本地_归档---")
        let filePath = path.isEmpty ? au_cache_accountPath : path
        let data = NSMutableData()
        let archive = NSKeyedArchiver(forWritingWith: data)
        archive.encode(self, forKey: key)
        archive.finishEncoding()
        return data.write(toFile: filePath, atomically: true)
    }
}
